<template>
  <div class="my-likes">
    <LoadingWrapper :loading="loading">
      <div>
        <el-tabs v-model="activeTab">
          <el-tab-pane label="全部" name="all">
            <div v-if="likedBooks.length > 0" class="book-grid">
              <div class="book-card" v-for="book in paginatedLikes" :key="book.id">
                <div class="image-wrapper">
                  <el-image 
                    :src="getBookImage(book)" 
                    class="book-image" 
                    alt="book cover"
                    @error="handleImageError"
                  >
                    <template #error>
                      <div class="image-placeholder">
                        <el-icon><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                </div>
                <div class="book-info">
                  <div class="book-header">
                    <h3 class="book-title">{{ book.title }}</h3>
                    <div class="book-meta-info">
                      <div class="book-author">作者：{{ book.author }}</div>
                      <div class="book-sharer">分享者：{{ book.username }}</div>
                    </div>
                  </div>
                  <div class="book-content">
                    <p class="book-description">{{ book.thoughts }}</p>
                    <div class="tags">
                      <el-tag v-for="tag in parseTags(book.tags)" :key="tag" size="small">
                        {{ tag }}
                      </el-tag>
                    </div>
                  </div>
                  <div class="book-footer">
                    <div class="stats">
                      <div class="left-stats">
                        <span class="likes" @click="handleUnlike(book)">
                          <heart-outline-icon 
                            :size="16" 
                            color="#ff4757"
                            :filled="true"
                          />
                          {{ book.like_count }}
                        </span>
                        <div class="rating">
                          <span class="rating-label">综合评分:</span>
                          <span class="rating-value">{{ Math.round(book.rating || 0) }}分</span>
                        </div>
                      </div>
                      <div class="right-action">
                        <el-button type="primary" link @click="goToDetail(book)">
                          查看详情
                          <el-icon class="el-icon--right"><ArrowRight /></el-icon>
                        </el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <el-empty v-else description="暂无点赞数据" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </LoadingWrapper>

    <PaginationBar
      v-if="likedBooks.length > 0"
      v-model:currentPage="currentPage"
      v-model:pageSize="pageSize"
      :total="likedBooks.length"
      :pageSizes="[4, 8, 12, 16]"
      @pagination-change="handlePaginationChange"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowRight, Picture } from '@element-plus/icons-vue'
import HeartOutlineIcon from '@/components/icons/HeartOutlineIcon.vue'
import { getLikedBooks, unlikeBook } from '@/api/book'
import PaginationBar from '@/components/pagination/PaginationBar.vue'
import LoadingWrapper from '@/components/loading/LoadingWrapper.vue'

const router = useRouter()
const activeTab = ref('all')
const likedBooks = ref([])
const currentPage = ref(1)
const pageSize = ref(4)
const loading = ref(true)

// 获取图片URL
const getBookImage = (book) => {
  try {
    if (book.images) {
      const images = typeof book.images === 'string' ? 
        JSON.parse(book.images) : 
        book.images
      return images[0] || ''
    }
    return ''
  } catch (error) {
    console.error('解析图片数据失败:', error)
    return ''
  }
}

// 处理图片加载错误
const handleImageError = (e) => {
  e.target.style.display = 'none'
}

// 加载点赞列表
const getLikesList = async () => {
  try {
    loading.value = true
    const res = await getLikedBooks()
    if (res.code === 200) {
      likedBooks.value = res.data.map(book => {
        try {
          if (book.images) {
            book.images = typeof book.images === 'string' ? 
              JSON.parse(book.images) : 
              book.images
          } else {
            book.images = []
          }
        } catch (e) {
          console.error('解析图片数据失败:', e)
          book.images = []
        }
        return book
      })
    }
  } catch (error) {
    console.error('获取点赞列表失败:', error)
    ElMessage.error('获取点赞列表失败')
  } finally {
    loading.value = false
  }
}

// 跳转到详情页
const goToDetail = (book) => {
  const routeData = router.resolve({
    name: 'BookDetail',
    params: { id: book.id }
  })
  window.open(routeData.href, `详情-${book.title}`)
}

// 取消点赞
const handleUnlike = async (book) => {
  try {
    await unlikeBook(book.id)
    ElMessage.success('已取消点赞')
    getLikesList()   
  } catch (error) {
    console.error('取消点赞失败:', error)
    ElMessage.error('取消点赞失败')
  }
}

// 解析标签
const parseTags = (tags) => {
  if (!tags) return []
  if (Array.isArray(tags)) return tags
  if (typeof tags === 'string') {
    return tags.split(/\s+/).filter(Boolean)
  }
  return []
}

// 分页后的点赞列表
const paginatedLikes = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return likedBooks.value.slice(start, end)
})

// 处理分页变化
const handlePaginationChange = ({ type, value }) => {
  if (type === 'page') {
    currentPage.value = value
  } else if (type === 'size') {
    pageSize.value = value
    currentPage.value = 1  // 重置到第一页
  }
}

// 在组件挂载时加载数据
onMounted(() => {
  getLikesList()
})
</script>

<style scoped>
.my-likes {
  padding: 20px;

  h2 {
    margin-bottom: 24px;
    font-size: 24px;
    font-weight: 600;
    color: #333;
  }

  .book-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 24px;
    padding: 4px;
  }

  .book-card {
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
    overflow: hidden;
    transition: all 0.3s ease;
    display: flex;
    flex-direction: column;
  }

  .book-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  }

  .book-image {
    width: 100%;
    height: 220px;
    object-fit: cover;
    transition: transform 0.3s ease;
  }

  .book-card:hover .book-image {
    transform: scale(1.05);
  }

  .book-info {
    padding: 20px;
    display: flex;
    flex-direction: column;
    flex: 1;
    gap: 16px;
  }

  .book-header {
    margin-bottom: 4px;
  }

  .book-title {
    margin: 0 0 8px 0;
    font-size: 18px;
    font-weight: bold;
    color: #333;
    line-height: 1.4;
  }

  .book-meta-info {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .book-author, .book-sharer {
    color: #666;
    font-size: 14px;
  }

  .book-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .book-description {
    color: #666;
    font-size: 14px;
    line-height: 1.6;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    margin: 0;
    height: auto;
    max-height: 66px;
  }

  .tags {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }

  .book-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: auto;
    padding-top: 16px;
    border-top: 1px solid #f0f0f0;
  }

  .stats {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .left-stats {
    display: flex;
    align-items: center;
    gap: 32px;
  }

  .likes {
    display: flex;
    align-items: center;
    gap: 6px;
    color: #ff4757;
    transition: all 0.3s;
    cursor: pointer;
    padding: 4px 8px;
    border-radius: 4px;
  }

  .likes:hover {
    background-color: rgba(255, 71, 87, 0.1);
  }

  .rating {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 4px 0;
  }

  .rating-label {
    color: #666;
    font-size: 14px;
  }

  .rating-value {
    font-size: 14px;
    color: #ff9900;
    font-weight: bold;
  }

  .right-action {
    padding: 4px 0;
  }

  :deep(.el-button--primary.el-button--link) {
    font-size: 14px;
  }

  :deep(.el-button--primary.el-button--link:hover) {
    opacity: 0.8;
  }

  /* 响应式调整 */
  @media screen and (max-width: 768px) {
    .book-grid {
      grid-template-columns: 1fr;
    }
    
    .book-image {
      height: 200px;
    }
  }

  /* 优化空状态样式 */
  :deep(.el-empty) {
    padding: 60px 0;
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  }

  :deep(.el-empty__description) {
    margin-top: 24px;
    font-size: 16px;
    color: #666;
  }
}
</style>